<template>
  <div class="warpper-box">
    <div class="inner_box">
     <form-create 
     v-model="params.fApi" 
     :rule="params.rule" 
     :option="params.option" 
     @btn-search-click="loadList(true)" 
     @btn-add-click="add(true)" 
     @btn-reset-click="reset"/>
    <system-list
     :key="keys"
     :tableData="tables.tableData" 
     :tableLabel="tables.tableLabel" 
     :models="tables" 
     @on-search-click="loadList"
     @on-edit-click="add"
     @on-del-click="del"
     @on-enable-click="onEnable"
     />
     
    <el-dialog :title="openPermission.title" :visible.sync="openPermission.visible" :width="openPermission.width" :close-on-click-modal="false">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="角色信息" :labelStyle="{'background': 'transparent','width':'100px'}">
          <form-create 
          v-model="openPermission.fApi" 
          :rule="openPermission.rule" 
          :option="openPermission.option" />
        </el-descriptions-item>
       
        <el-descriptions-item label="权限" :labelStyle="{'background': 'transparent'}">
          <el-tree 
          :props="openPermission.menuProps" 
          :data="openPermission.menuData"
          ref="menuTree"
          node-key="id"
          show-checkbox
          @check="handleCheckChange">
        </el-tree>
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="resetChecked">重置</el-button>
        <el-button type="primary" size="small" @click="onFormSubmit">提交</el-button>
      </div>
    </el-dialog>

    </div>
  </div>
</template>

<script>
import store from '@/store'
import { 
PARAMS_ROLE,
FORM_ROLE,
OPTION_INLINE,
ROLE_LABEL,
OPTION_BLOCK,
BTN_CODE,
BTN_PARENT,
BTN_CHILD,
API_CODE,
API_PARENT,
API_CHILD,
MENU_CODE,
MENU_PARENT
} from "./systemUser/system_form"
import { getRoleList,saveRole,delRole,disableRole,enableRole,getRolePermission} from "@/api/system_api"
import {getAllTree} from "@/api/common_api"
import SystemList from "./systemUser/system_list"
export default {
  components:{
    SystemList,
  },
  data() {
    return {
        keys:0,
        params:{
            fApi:{},
            rule:PARAMS_ROLE,
            option:OPTION_INLINE
        },
        tables:{
            total:0,
            width:'220',
            tableData:[],
            tableLabel: ROLE_LABEL
        },
        openPermission:{
            roleId: "", 
            roleName:'',
            width:"600px",
            title: "新增角色",
            visible: false,
            fApi:{},
            rule:[],
            option:OPTION_BLOCK,
            menuProps:{
              children: 'children',
              label: 'name',
              id:"id"
            },
            menuData:[],
            menuIds:[]
        },
        page:{
            pageNum:1,
            pageSize:10,
        }
    };
  },
  mounted() {
    this.loadList(true);
    this.$nextTick(()=>{
      this.params.fApi.setValue({"name":""});
    })
  },
  methods: {
    async loadList(formData) {
      let params = this.params.fApi.bind();
      if(formData !== undefined && formData.type === 'page'){
        this.page.pageNum = formData.page;
        this.page.pageSize = formData.pageSize;
      }
      if(formData===true){
        this.page.pageNum = 1;
        this.keys++;
      }
      params.pageNum = this.page.pageNum;
      params.pageSize = this.page.pageSize;
      const {data} = await getRoleList(params);
     // data.list = data.list.filter(v=>v.id !== 52);
      this.tables.tableData = data.list;
      this.tables.tableData.forEach(v => {
        v.edit = true; v.del = true;
        if(v.id == 52){
          v.isSwitch = true;
          v.del = false;
          v.edit = false;
        }
        if(v.statusFlag === '1'){
          v.enable = true;
        }else if(v.statusFlag === '0'){
          v.disable = true;
        }
      })
      this.tables.total = data.total;
    },
    
    add(row){
      this.openPermission.rule = FORM_ROLE;
      this.$nextTick(async()=>{
        if(row === true){
          this.openPermission.title = "新增角色";
          this.openPermission.roleId = "";
          this.openPermission.roleName = "";
          this.openPermission.fApi.resetFields();
          this.openPermission.menuData = await store.dispatch('user/getAllTree');
        }else{
          this.openPermission.title = "编辑角色";
          this.openPermission.roleId = row.id;
          this.openPermission.roleName = row.name;
          this.openPermission.fApi.setValue({
            "name":row.name,
            "description":row.description
          })
          this.onOpenPermission(row);
        }
      })
      this.openPermission.visible = true;
    },
    async onFormSubmit() {
      this.openPermission.fApi.submit(async (formData, $f) => {

        if(this.openPermission.menuIds.length === 0){
          this.$message.error("请勾选权限！");return;
        }

        if (!formData.description) {
          formData.description = ' '
        }
        
        let text = "新增成功";
        if(this.openPermission.roleId){
          formData.id = this.openPermission.roleId;
          text = "修改成功"
        }
        formData.menuIds = this.openPermission.menuIds;
        const req = await saveRole(formData);
        if (req.code == 200) {
          this.$message.success(text);
          this.openPermission.visible = false;
          this.openPermission.fApi.resetFields();
          this.loadList();
          this.resetChecked();
        }
      });
    },
    async onOpenPermission(row){
      let _this = this;
      
      _this.openPermission.menuData = await store.dispatch('user/getAllTree');
      let req = await getRolePermission(row.id);
      if(req.data && req.data.length !==0){
        if(_this.$refs.menuTree){
          _this.$nextTick(()=>{
            req.data.forEach(key=>{
              _this.openPermission.menuIds.push(key);
                _this.$refs.menuTree.setChecked(key, true, false);
            })
          })
        }
      }
    },
    resetChecked(){
      this.$refs.menuTree.setCheckedKeys([]);
      this.openPermission.menuIds=[];
      this.openPermission.fApi.resetFields();
    },
    handleCheckChange(node,data){
      let arrConcat = this.$refs.menuTree.getCheckedKeys().concat(this.$refs.menuTree.getHalfCheckedKeys());
        //arrConcat = data.checkedKeys.filter(v=>{return v!==undefined});
      var newArray = [];
      for(var i=0,len=arrConcat.length; i<len; i++) {
          if(newArray.indexOf(arrConcat[i]) === -1 && arrConcat[i] !== undefined) {
              newArray.push(arrConcat[i])
          }
      }
      this.openPermission.menuIds = newArray;
      
    },
    onEnable(row) {
      if (row.id === 52) {
        this.$message.error("供应商是固定角色，不允许修改！");
        return;
      }
      let text = row.statusFlag==='1' ?'禁用':'启用';
      let tips = row.statusFlag==='1' ?'禁用成功':'启用成功';
      this.$confirm("确认"+text+"", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        row.statusFlag === '1' ? await disableRole(row.id) : await enableRole(row.id);
        this.$message.success(tips);
        this.loadList();
      }).catch(() => {});
    },
    del(row){
      this.$confirm("确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        await delRole(row.id);
        this.$message.success("删除成功");
        this.loadList();
      }).catch(() => {});
    },
    reset(){
      this.params.fApi.resetFields();
      this.loadList(true);
    }
  }
};
</script>